import numpy as np

def gcc_phat(x1,x2):
    xf1 = np.fft.fft(x1)
    xf2 = np.fft.fft(x2)

    g = xf1 * np.conj(xf2)
    
    w = 1.0 / (np.abs(g) + np.finfo(np.float64).eps)
    
    gw = g*w
    
    r = np.fft.ifft(gw)

    r = np.fft.fftshift(r)
    return r


def time_delay(x1,x2,fs):
    r = gcc_phat(x1,x2)
    max_idx = np.argmax(np.abs(r))
    N = len(x1)
    delay = (max_idx - N // 2) / fs
    return delay